package com.atguigu.gmall.product.service.impl;
import com.atguigu.gmall.common.cache.GmallCache;
import com.atguigu.gmall.common.constant.RedisConst;
import com.atguigu.gmall.model.product.*;
import com.atguigu.gmall.mq.config.MqConst;
import com.atguigu.gmall.product.mapper.*;
import com.atguigu.gmall.product.service.ManagerService;
import com.atguigu.gmall.service.RabbitService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.math.BigDecimal;
import java.util.*;
import java.util.concurrent.TimeUnit;

/**
 * @author ：MJS
 * @date ：Created in 2021/5/8  20:40
 * @description：产品类的接口
 */
@Service
public class ManagerServiceImpl implements ManagerService {

    @Autowired
    private BaseCategory1Mapper baseCategory1Mapper;
    @Autowired
    private BaseCategory2Mapper baseCategory2Mapper;
    @Autowired
    private BaseCategory3Mapper baseCategory3Mapper;
    @Autowired
    private BaseAttrInfoMapper baseAttrInfoMapper;
    @Autowired
    private BaseAttrValueMapper baseAttrValueMapper;
    @Autowired
    private BaseTrademarkMapper baseTrademarkMapper;
    @Autowired
    private SpuInfoMapper spuInfoMapper;
    @Autowired
    private BaseSaleAttrMapper baseSaleAttrMapper;
    @Autowired
    private SpuImageMapper spuImageMapper;
    @Autowired
    private SpuSaleAttrMapper spuSaleAttrMapper;
    @Autowired
    private SpuSaleAttrValueMapper spuSaleAttrValueMapper;
    @Autowired
    private SkuInfoMapper skuInfoMapper;
    @Autowired
    private SkuImageMapper skuImageMapper;
    @Autowired
    private SkuAttrValueMapper skuAttrValueMapper;
    @Autowired
    private SkuSaleAttrValueMapper skuSaleAttrValueMapper;
    @Autowired
    private BaseCategoryViewMapper baseCategoryViewMapper;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private RedissonClient redissonClient;//解决分布式及分布式锁的相关问题
    @Autowired
    private RabbitService rabbitService;
    //查询一级分类的集合
    @Override
    public List<BaseCategory1> getCategory1() {
        return baseCategory1Mapper.selectList(null);
    }
    //查询二级分类的集合
    @Override
    public List<BaseCategory2> getCategory2(Long category1Id) {
        QueryWrapper queryWrapper=new QueryWrapper();
        queryWrapper.eq("category1_id",category1Id);
        return baseCategory2Mapper.selectList(queryWrapper);
    }
    //查询三级分类的集合
    @Override
    public List<BaseCategory3> getCategory3(Long category2Id) {
        QueryWrapper queryWrapper=new QueryWrapper();
        queryWrapper.eq("category2_id",category2Id);
        return baseCategory3Mapper.selectList(queryWrapper);
    }
    //根据一二三级分类Id  层级查询  平台属性及属性值表
    @Override
    public List<BaseAttrInfo> attrInfoList(Long category1Id, Long category2Id, Long category3Id) {
        return baseAttrInfoMapper.attrInfoList(category1Id,category2Id,category3Id);
    }
    //添加或修改平台属性及值
    @Override
    public void saveAttrInfo(BaseAttrInfo baseAttrInfo) {
        if(baseAttrInfo.getAttrName()!=null){
            baseAttrInfoMapper.updateById(baseAttrInfo);
            List<BaseAttrValue> attrValueList = baseAttrInfo.getAttrValueList();
            attrValueList.forEach(baseAttrValue -> {
                baseAttrValueMapper.updateById(baseAttrValue);
            });
        }else{
        //1.平台属性表  1   1
        baseAttrInfoMapper.insert(baseAttrInfo);
        //2.平台属性值表
        List<BaseAttrValue> attrValueList = baseAttrInfo.getAttrValueList();
        attrValueList.forEach(baseAttrValue -> {
            //外键
            baseAttrValue.setAttrId(baseAttrInfo.getId());
            baseAttrValueMapper.insert(baseAttrValue);
        });
        }
    }
    //分页查询品牌列表
    @Override
    public IPage baseTrademark(Integer page, Integer limit) {
       Page<BaseTrademark> pageParam = new Page(page, limit);
        return baseTrademarkMapper.selectPage(pageParam, null);
    }
    //根据属性id查询平台属性及值

    @Override
    public List<BaseAttrValue> getAttrValueList(Long attrId) {
        QueryWrapper queryWrapper=new QueryWrapper();
        queryWrapper.eq("attr_id",attrId);
        List valueList = baseAttrValueMapper.selectList(queryWrapper);
        return valueList;

    }
    //获取spu分页列表
    @Override
    public IPage getSpuByPage(Integer page, Integer limit,Long category3Id) {
        Page pageParam=new Page(page,limit);
        QueryWrapper queryWrapper=new QueryWrapper();
        queryWrapper.eq("category3_id",category3Id);
        return spuInfoMapper.selectPage(pageParam,queryWrapper);
    }

    //获取销售属性
    @Override
    public List<BaseSaleAttr> baseSaleAttrList() {
        return baseSaleAttrMapper.selectList(null);
    }
    //获取品牌属性
    @Override
    public List<BaseTrademark> getTrademarkList() {
        return baseTrademarkMapper.selectList(null);
    }
    //商品添加
    @Override
    public void saveSpuInfo(SpuInfo spuInfo) {
        //1商品表
        spuInfoMapper.insert(spuInfo);
        //2图片表
        List<SpuImage> spuImageList = spuInfo.getSpuImageList();
        //这里最好都判断一下空值
        if(!CollectionUtils.isEmpty(spuImageList)){
            spuImageList.forEach(spuImage -> {
                //外键
                spuImage.setSpuId(spuInfo.getId());
                spuImageMapper.insert(spuImage);
            });
        }
        //3销售属性表
        List<SpuSaleAttr> spuSaleAttrList = spuInfo.getSpuSaleAttrList();
        //判断
        if(!CollectionUtils.isEmpty(spuSaleAttrList)){
            spuSaleAttrList.forEach(spuSaleAttr -> {
                //外键
                spuSaleAttr.setSpuId(spuInfo.getId());
                spuSaleAttrMapper.insert(spuSaleAttr);
                //4销售属性值表
                List<SpuSaleAttrValue> spuSaleAttrValueList = spuSaleAttr.getSpuSaleAttrValueList();
                //判断
                if(!CollectionUtils.isEmpty(spuSaleAttrValueList)){
                    spuSaleAttrValueList.forEach(spuSaleAttrValue -> {
                        spuSaleAttrValue.setSpuId(spuInfo.getId());
                        spuSaleAttrValue.setSaleAttrName(spuSaleAttr.getSaleAttrName());
                        spuSaleAttrValueMapper.insert(spuSaleAttrValue);
                    });

                }
            });

        }
    }
    //根据spuId获取图片列表  显示Sku添加页面   目标为了让管理员选择
    @Override
    public List<SpuImage> spuImageList(Long spuId) {
        QueryWrapper<SpuImage>queryWrapper=new QueryWrapper();
        queryWrapper.eq("spu_id",spuId);
        return spuImageMapper.selectList(queryWrapper);
    }
    //根据SpuId查询销售属性及属性值
    @Override
    public List<SpuSaleAttr> spuSaleAttrList(Long spuId) {
        return spuSaleAttrMapper.spuSaleAttrList(spuId);
    }
    //添加库存
    @Override
    public void saveSkuInfo(SkuInfo skuInfo) {
        //1库存表
        skuInfoMapper.insert(skuInfo);
        //2库存的图片表
        List<SkuImage> skuImageList = skuInfo.getSkuImageList();
          //判断
        if(!CollectionUtils.isEmpty(skuImageList)){
            skuImageList.forEach(skuImage -> {
                skuImage.setSkuId(skuInfo.getId());
                skuImageMapper.insert(skuImage);
            });
        }
        //3库存与平台属性的及值得中间表
        List<SkuAttrValue> skuAttrValueList = skuInfo.getSkuAttrValueList();
        //判断
        if(!CollectionUtils.isEmpty(skuAttrValueList)){
            skuAttrValueList.forEach(skuAttrValue -> {
                skuAttrValue.setSkuId(skuInfo.getId());
                skuAttrValueMapper.insert(skuAttrValue);
            });
        }
        //4库存与销售属性及值得中间表
        List<SkuSaleAttrValue> skuSaleAttrValueList = skuInfo.getSkuSaleAttrValueList();
        //判断
        if(!CollectionUtils.isEmpty(skuSaleAttrValueList)){
            skuSaleAttrValueList.forEach(skuSaleAttrValue -> {
                skuSaleAttrValue.setSkuId(skuInfo.getId());
                skuSaleAttrValue.setSpuId(skuInfo.getSpuId());
                skuSaleAttrValueMapper.insert(skuSaleAttrValue);
            });
        }
    }
    //获取sku分页列表
    @Override
    public IPage<SkuInfo> list(Integer page, Integer limit) {
        Page pageParam = new Page(page, limit);
        return skuInfoMapper.selectPage(pageParam,null);
    }
    //上架
    @Override
    public void onSale(Long skuId) {
        //1、修改DB中库存表 is_sale
        //1.1update sku_info set is_sale =1 where id =?
        SkuInfo skuInfo = new SkuInfo();
        skuInfo.setId(skuId);
        skuInfo.setIsSale(SkuInfo.ISSALE);//问题：硬编码问题
        skuInfoMapper.updateById(skuInfo);
        //2、发消息更新ES索引库
        rabbitService.sendMessage(MqConst.EXCHANGE_DIRECT_GOODS,
                MqConst.ROUTING_GOODS_UPPER,
                skuId);

    }
    //下架
    @Override
    public void cancelSale(Long skuId) {
        //1、修改DB中库存表 is_sale
        //1.1update
        SkuInfo skuInfo = new SkuInfo();
        skuInfo.setId(skuId);
        skuInfo.setIsSale(SkuInfo.CANCELSALE);//问题：硬编码问题
        skuInfoMapper.updateById(skuInfo);
        //2、发消息，删除索引库
        rabbitService.sendMessage(MqConst.EXCHANGE_DIRECT_GOODS,
                MqConst.ROUTING_GOODS_LOWER,skuId);

    }
    //1.根据SKUID获取SKUINFO信息  图片
    // 直接使用RedissonClient来解决分布式锁的问题
    @Override
    public SkuInfo getSkuInfo(Long skuId) {
        //缓存key值
        String cacheKey = RedisConst.SKUKEY_PREFIX + skuId + RedisConst.SKUKEY_SUFFIX;
        //1.先查询缓存
        SkuInfo skuInfo=(SkuInfo)redisTemplate.opsForValue().get(cacheKey);
        //没有缓存
        if(null==skuInfo){
            //上锁  解决缓存击穿   分布式锁的key
            String cacheLockKey = RedisConst.SKUKEY_PREFIX + skuId + RedisConst.SKULOCK_SUFFIX;
            RLock lock = redissonClient.getLock(cacheLockKey);
            //过期不候的锁  JUC
            //参数1：获取锁的时间  过了这个时间就不在获取了
            //参数2：获取到锁之后  锁的  过期时间
            //参数3：单位
            try {
                boolean tryLock = lock.tryLock(1, 4, TimeUnit.SECONDS);
                if(tryLock){
                    //获取到了锁
                    //2.没有   查询DB
                    skuInfo=skuInfoMapper.selectById(skuId);
                    if(null != skuInfo){
                        skuInfo.setSkuImageList(skuImageMapper.
                                selectList(new QueryWrapper<SkuImage>().eq("sku_id",skuId)));
                    //再保存缓存一份
                        redisTemplate.opsForValue().set(cacheKey,skuInfo,
                                RedisConst.SKUKEY_TIMEOUT+new Random().nextInt(300),//缓存雪崩
                                TimeUnit.SECONDS);
                    }else{
                        //缓存 穿透  空结果  应付攻击者 DB
                        skuInfo=new SkuInfo();
                        //再保存缓存一份
                        redisTemplate.opsForValue().set(cacheKey,skuInfo,5,TimeUnit.MINUTES);
                    }
                    //解锁
                    lock.unlock();
                }else {
                    try {
                        //未获取锁
                        Thread.sleep(2000);
                        return (SkuInfo)redisTemplate.opsForValue().get(cacheKey);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        //统一返回
        return skuInfo;
    }

    /*@Override
        public SkuInfo getSkuInfo(Long skuId) {
            //缓存key值
            String cacheKey = RedisConst.SKUKEY_PREFIX+skuId+RedisConst.SKUKEY_SUFFIX;
            //1.先查询缓存
            SkuInfo skuInfo = (SkuInfo)redisTemplate.opsForValue().get(cacheKey);
            //3.没有  先查询Db  在保存一份  返回
            if(null==skuInfo){
                //分布式锁的key值
                String cacheLockKey=RedisConst.SKUKEY_PREFIX+skuId+RedisConst.SKULOCK_SUFFIX;
                //解决缓存击穿问题  上分布式锁   加过期时间 防止死锁
                //UUID   36长度   去掉四个小横线
                String uuid = UUID.randomUUID().toString().replace("-", "");
                Boolean lock = redisTemplate.opsForValue().setIfAbsent(cacheLockKey, uuid,1,TimeUnit.SECONDS);
                if(lock){
                    //获取到锁
                    //2.没有  查询DB
                    skuInfo = skuInfoMapper.selectById(skuId);
                    if(null !=skuInfo){
                        skuInfo.setSkuImageList(skuImageMapper.selectList(
                                new QueryWrapper<SkuImage>().eq("sku_id",skuId)
                        ));
                        //保存缓存一份    解决缓存雪崩问题
                        redisTemplate.opsForValue().set(cacheKey,skuInfo,RedisConst.SKUKEY_TIMEOUT+new Random().nextInt(300), TimeUnit.SECONDS);
                    }else{
                        //解决缓存穿透  空结果
                        skuInfo = new SkuInfo();
                        //再保存缓存一份
                        redisTemplate.opsForValue().set(cacheKey,skuInfo,300, TimeUnit.SECONDS);
                    }
                    //删除锁
                    //判断是否是自己的锁   防止误删
                    *//*  不符合原子性
                Object u = redisTemplate.opsForValue().get(cacheLockKey);
                if(uuid.equals(u)) {
                    redisTemplate.delete(cacheLockKey);
                }*//*
                //LUA脚本    nginx或redis
                //准备脚本  删除要准备原子性
                String script = "if redis.call('get', KEYS[1]) == ARGV[1] then return tostring(redis.call('del',KEYS[1])) else return 0 end";
                this.redisTemplate.execute(new DefaultRedisScript<>(script), Collections.singletonList(cacheLockKey), uuid);
            }else{
                //未获取到锁，
                try {
                    TimeUnit.SECONDS.sleep(3);
                    //查询缓存
                    return (SkuInfo)redisTemplate.opsForValue().get(cacheKey);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

            }
        }
        //2.统一返回
        return skuInfo;
    }*/
    //2.三级分类的视图
    @Override
    @GmallCache(prefix = "baseCategoryView:")
    public BaseCategoryView getBaseCategoryView(Long category3Id) {
        return baseCategoryViewMapper.selectById(category3Id);
    }
    //3.销售属性及值及选中红边框

    @Override
    @GmallCache(prefix = "getSpuSaleAttrValueChecked:")
    public List<SpuSaleAttr> getSpuSaleAttrValueChecked(Long skuId, Long spuId) {
        return spuSaleAttrMapper.getSpuSaleAttrValueChecked(skuId,spuId);
    }
    //4.销售值组合对应的skuId
    //入参：商品ID spuId   手写SQL
    @Override
    @GmallCache(prefix = "getValuesSkuJson:")
    public Map getValueSkuJson(Long spuId) {
        Map result=new HashMap();
        List<Map>listMap=skuSaleAttrValueMapper.getValueSkuJson(spuId);
        listMap.forEach(map -> {
            result.put(map.get("valueIds"),map.get("sku_id"));
        });
        return result;
    }
    //5.单独查询价格 不放在缓存中
    @Override
    public BigDecimal getPrice(Long skuId) {
        SkuInfo skuInfo = skuInfoMapper.selectById(skuId);
        if(null !=skuInfo){
            return skuInfo.getPrice();
        }else {
            return null;
        }
    }
    //查询三级分类视图集合
    @Override
    public List<BaseCategoryView> getBaseCategoryViewList() {
        return baseCategoryViewMapper.selectList(null);
    }

    //根据主键查询品牌对象
    @Override
    public BaseTrademark getBaseTrademark(Long id) {
        return baseTrademarkMapper.selectById(id);
    }
    //查询ES索引库所需要的平台属性ID及名称及值
    @Override
    public List<SkuAttrValue> getSkuAttrValue(Long skuId) {
        return skuAttrValueMapper.getSkuAttrValue(skuId);
    }
}
